package com.express.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonResponse;
import com.express.mybatis.Result;
import com.express.service.MessageService;
import com.express.util.SmsAlidayu;
import com.github.pagehelper.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 *  短信消息实现类
 */
@Service
public class MessageServiceImpl implements MessageService {
  private Logger logger = LoggerFactory.getLogger(getClass());
  private static Map<String, HttpSession> sendVerCode = new HashMap();
  private  String ALIDAYU_SMS_SIGN = "广州莱比特";
  private  String ALIDAYU_SMS_TEMPLATE_CODE = "SMS_171905923";
  private  String ALIDAYU_SMS_TEMPLATE_PASSWORD = "SMS_172742927";
  private  String ALIDAYU_SMS_TEMPLATE_COUPON = "SMS_180352504";
  private  String ALIDAYU_SMS_TEMPLATE_REGIST = "SMS_205350052";

  /**
   * 发送短信
   * @param request
   * @param mobile
   * @return
   */
  @Override
  public Result send(HttpServletRequest request, String mobile) {
    try {
      String verCode = getCode();
      this.logger.info("短信验证码===" + verCode);
      HttpSession session = request.getSession();
      session.setAttribute("SMS_MOBILE", mobile);
      session.setAttribute("SMS_VERCODE", verCode);
      sendVerCode.put(mobile, session);
      Map<String, String> param = new HashMap();
      param.put("code", verCode);

      CommonResponse commonResponse = SmsAlidayu.sendSms2(mobile, this.ALIDAYU_SMS_SIGN, this.ALIDAYU_SMS_TEMPLATE_REGIST, param);
      if ((commonResponse.getData() != null) && (JSON.parseObject(commonResponse.getData()).get("Code").equals("OK"))) {
        return new Result();
      }
      return new Result();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new Result("发送短信失败", 500, false);
  }

  /**
   *  生成随机的验证码
   * @return
   */
  public static String getCode() {
    int code = (int) ((Math.random() * 9.0D + 1.0D) * 100000.0D);
    return code + "";
  }

  @Override
  public Boolean verifyCode(HttpServletRequest request, String mobile, String code) {
    try {
      HttpSession session = (HttpSession) sendVerCode.get(mobile);

      String verMobile = (String) session.getAttribute("SMS_MOBILE");
      String verCode = (String) session.getAttribute("SMS_VERCODE");
      if (StringUtil.isEmpty(verCode)) {
        return Boolean.valueOf(false);
      }
      if ((mobile.equals(verMobile)) && (code.equals(verCode))) {
        return Boolean.valueOf(true);
      }
    } catch (Exception e) {
      e.printStackTrace();
      return Boolean.valueOf(false);
    }
    return Boolean.valueOf(false);
  }
}